﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CosAging.Class
{
    internal class communication
    {
        private static SerialPort serialPort;
        private static LinkedList<string> commandList;
        static void SET()
        {
            string portName = "COM1";  // 串口名称
            int baudRate = 9600;  // 波特率

            // 初始化串口
            serialPort = new SerialPort(portName, baudRate);
            serialPort.DataReceived += SerialPort_DataReceived;

            // 初始化命令列表
            commandList = new LinkedList<string>();
            commandList.AddLast("Command1");
            commandList.AddLast("Command2");
            commandList.AddLast("Command3");

            try
            {
                // 打开串口
                serialPort.Open();
                Console.WriteLine("串口已打开。");

                SendCommands();

                Console.ReadLine();  // 等待用户输入
            }
            catch (Exception ex)
            {
                Console.WriteLine("无法打开串口：" + ex.Message);
            }
            finally
            {
                // 关闭串口
                if (serialPort != null && serialPort.IsOpen)
                {
                    serialPort.Close();
                }
            }
        }
        private static void SendCommands()
        {
            string SEND = commandList.ElementAt(0);


            foreach (string command in commandList)
            {
                Console.WriteLine("发送命令: " + command);
                serialPort.WriteLine(command);
            }
        }
        private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string receivedData = serialPort.ReadExisting();
            Console.WriteLine("收到数据: " + receivedData);
        }
    }
}
